from django.db import models
from django.conf import settings

class Delivery(models.Model):
    STATUS_CHOICES = (
        ('pending', '待配送'),
        ('in_progress', '配送中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    )

    order = models.OneToOneField('orders.Order', on_delete=models.CASCADE, related_name='delivery')
    deliveryman = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='deliveries')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
    delivery_time = models.DateTimeField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = '配送任务'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'配送任务 #{self.id} - {self.order}'

class DeliveryRoute(models.Model):
    delivery = models.OneToOneField(Delivery, on_delete=models.CASCADE, related_name='route', verbose_name='配送记录')
    start_location = models.CharField(max_length=200, verbose_name='起始位置')
    end_location = models.CharField(max_length=200, verbose_name='目的地')
    estimated_distance = models.FloatField(verbose_name='预计距离(公里)')
    estimated_time = models.IntegerField(verbose_name='预计时间(分钟)')
    actual_distance = models.FloatField(null=True, blank=True, verbose_name='实际距离(公里)')
    actual_time = models.IntegerField(null=True, blank=True, verbose_name='实际时间(分钟)')
    
    class Meta:
        verbose_name = '配送路线'
        verbose_name_plural = verbose_name

class DeliveryLog(models.Model):
    delivery = models.ForeignKey(Delivery, on_delete=models.CASCADE, related_name='logs', verbose_name='配送记录')
    location = models.CharField(max_length=200, verbose_name='当前位置')
    status = models.CharField(max_length=20, choices=Delivery.STATUS_CHOICES, verbose_name='配送状态')
    note = models.TextField(verbose_name='日志备注', blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='记录时间')
    
    class Meta:
        verbose_name = '配送日志'
        verbose_name_plural = verbose_name
